package com.ysd.controller;





import java.util.HashMap;

import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ysd.dao.userDao;
import com.ysd.entity.User;
import com.ysd.service.rolesService;
import com.ysd.service.userService;

/**
 * 用户
 * 
 * @author CJP
 *
 */
@RestController
public class userController{
	@Autowired
	userDao uo;
	@Autowired
	userService us;
	@Autowired
	rolesService rs;

	@RequestMapping("/getAll")
	public Map<String, Object> getA(Integer page, Integer limit, String uloginname) {
		// 分頁查詢
		Pageable p = new PageRequest(page-1, limit);
		Page<User> findAll = uo.findAll(getSs(uloginname),p);
		List<User> data = findAll.getContent();
		long count = findAll.getTotalElements();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "");
		map.put("data", data);
		map.put("count", count);
		return map;
	}
	
	private Specification<User> getSs(String uloginname) {
		// TODO Auto-generated method stub
		return new Specification<User>() {

			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate p=criteriaBuilder.conjunction();//构建动态SQL表达式
				List<Expression<Boolean>> list=p.getExpressions();//动态SQL的集合
				//根据名称和锁定模糊查询
				if(!StringUtils.isEmpty(uloginname)) {
					list.add(criteriaBuilder.like(root.get("uloginname"), "%"+uloginname+"%"));
				}
				
				return p;
			}
		};
	}
	
	//添加修改
	@RequestMapping("/addUser")
	public Integer addUser(User u) {
	return us.addUser(u);
	}
	// 删除
	@RequestMapping("/delUser")
	public Integer delUser(Integer uid) {
	return us.delUser(uid);
}
	//密码重置
	@ResponseBody
	@RequestMapping("/resetPwd")
	public Object resetPwd(Integer id) {
		try {
			us.ResetPwdById(id);
		} catch (Exception e) {
			// TODO: handle exception
			return "重置失败";
		}
		System.out.println(id);
		System.out.println(us.ResetPwdById(id));
		return "重置成功,初始密码 123456";
	}
	//是否锁定
	@ResponseBody
	@RequestMapping("/updateLock")
	public Object updateLock(Integer id,String lock) {
		try {
			if (lock.equals("是")) {
				us.updateLockById("否",id);
			} else {
				us.updateLockById("是",id);
			}
		} catch (Exception e) {
			// TODO: handle exception
			return "修改失败";
		}
		return "修改成功";
	}
	

}

